#include "Authentication.h"

#include "UserDatabase.h"
#include "PersonDatabase.h"

#include "Administrator.h"
#include "Doctor.h"
#include "Nurse.h"
#include "Patient.h"

#include <QMessageBox>

// Authentication singleton instantiation
Authentication * Authentication::authInst = new Authentication();

Authentication::Authentication()
{
    currentUser = nullptr;
    extraUser = nullptr;
}

User * Authentication::getUser()
{
    return currentUser;
}

Authentication * Authentication::getInstance()
{
    return authInst;
}

bool Authentication::login(QString username, QString password)
{
    UserDatabase userDB;

    int id = userDB.getId(username, password);
    if (id == UserDatabase::FAILURE)
        return false;

    int type = userDB.getType(id);

    // Create user object
    switch(type)
    {
    case User::ADMIN:
        currentUser = new Administrator(); break;

    case User::DOCTOR:
        currentUser = new Doctor(); break;

    case User::NURSE:
        currentUser = new Nurse(); break;

    case User::PATIENT:
        currentUser = new Patient(); break;

    default:
        return false;
    }

    // Get user information
    PersonDatabase personDB;
    PersonInfo info = personDB.getInfo(id);

    currentUser->setUserId(id);
    currentUser->setInfo(info);
    currentUser->setUsername(username);

    // Clear current patient from previous login
    if (extraUser != nullptr)
    {
        delete extraUser;
        extraUser = nullptr;
    }

    // Login successful
    return true;
}

bool Authentication::setPatient(int userId)
{
    if (extraUser != nullptr)
        delete extraUser;

    PersonDatabase personDB;
    PersonInfo info = personDB.getInfo(userId);

    Patient * patient = new Patient();
    patient->setUserId(userId);
    patient->setInfo(info);

    extraUser = patient;

    return true;
}


User * Authentication::getPatient()
{
    return extraUser;
}

Authentication::~Authentication()
{
    if (currentUser != nullptr)
        delete currentUser;
    if (extraUser != nullptr)
        delete extraUser;
}
